<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>新增巡检单</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="cancel">返回</el-button>
      </div>

      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <!-- 基础信息部分 -->
        <el-divider content-position="left">基础信息</el-divider>
        <el-form-item label="巡检编号" prop="recordCode">
          <el-input v-model="form.recordCode" placeholder="系统自动生成" disabled />
        </el-form-item>

        <el-form-item label="巡检计划" prop="planId">
          <el-select 
            v-model="form.planId" 
            placeholder="请选择关联巡检计划" 
            clearable 
            @change="handlePlanChange"
            style="width: 100%"
          >
            <el-option
              v-for="item in planOptions"
              :key="item.planId"
              :label="item.planName"
              :value="item.planId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="巡检设备" prop="equipmentId">
          <el-select 
            v-model="form.equipmentId" 
            placeholder="请选择巡检设备" 
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="item in equipmentOptions"
              :key="item.equipmentId"
              :label="item.equipmentName"
              :value="item.equipmentId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="巡检人" prop="inspectorName">
          <el-input v-model="form.inspectorName" placeholder="请输入巡检人姓名" />
        </el-form-item>

        <el-form-item label="巡检日期" prop="inspectionDate">
          <el-date-picker
            v-model="form.inspectionDate"
            type="date"
            placeholder="选择巡检日期"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="开始时间" prop="inspectionStartTime">
          <el-time-picker
            v-model="form.inspectionStartTime"
            placeholder="选择开始时间"
            value-format="HH:mm:ss"
            format="HH:mm:ss"
            :clearable="true"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="巡检状态" prop="inspectionStatus">
          <el-radio-group v-model="form.inspectionStatus">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{ dict.dictLabel }}</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <!-- 巡检项部分 -->
        <el-divider content-position="left">巡检项目</el-divider>
        
        <div style="margin-bottom: 20px;">
          <el-button type="primary" @click="addInspectionItem">添加巡检项</el-button>
        </div>

        <el-table :data="form.inspectionItems" border style="width: 100%" empty-text="请先选择巡检计划或添加巡检项">
          <el-table-column type="index" width="50" label="序号" />
          <el-table-column prop="itemName" label="巡检项名称" min-width="120">
            <template slot-scope="scope">
              <el-input v-model="scope.row.itemName" placeholder="请输入巡检项名称" :disabled="!!scope.row.itemId" />
            </template>
          </el-table-column>
          <el-table-column prop="itemStandard" label="巡检标准" min-width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.itemStandard" placeholder="请输入巡检标准" :disabled="!!scope.row.itemId" />
            </template>
          </el-table-column>
          <el-table-column prop="checkValue" label="检测值" min-width="120">
            <template slot-scope="scope">
              <el-input v-model="scope.row.checkValue" placeholder="请输入检测值" />
            </template>
          </el-table-column>
          <el-table-column prop="checkResult" label="检测结果" width="120">
            <template slot-scope="scope">
              <el-select v-model="scope.row.checkResult" placeholder="请选择">
                <el-option label="正常" value="0" />
                <el-option label="异常" value="1" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="requireImage" label="图片必传" width="100">
            <template slot-scope="scope">
              <el-tag :type="scope.row.requireImage === '1' ? 'success' : 'info'">
                {{ scope.row.requireImage === '1' ? '是' : '否' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" align="center">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteItem(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 其他信息部分 -->
        <el-divider content-position="left">其他信息</el-divider>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" rows="3" placeholder="请输入备注" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 新增巡检项弹窗 -->
      <el-dialog title="新增巡检项" :visible.sync="itemDialog.visible" width="500px" append-to-body>
        <el-form ref="itemForm" :model="itemForm" :rules="itemRules" label-width="100px">
          <el-form-item label="巡检项名称" prop="itemName">
            <el-input v-model="itemForm.itemName" placeholder="请输入巡检项名称" />
          </el-form-item>
          <el-form-item label="巡检标准" prop="itemStandard">
            <el-input v-model="itemForm.itemStandard" type="textarea" :rows="3" placeholder="请输入巡检标准" />
          </el-form-item>
          <el-form-item label="图片必传">
            <el-switch v-model="itemForm.requireImage" active-value="1" inactive-value="0" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="itemDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitItemForm">确定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { addInspectionRecord, getInspectionPlanList } from '@/api/sb/inspectionRecord'
import { getAvailableEquipments, getAllEquipments } from '@/api/sb/inspectionPlan'
import { getItemsByConfigId } from '@/api/sb/inspectionItem'
import { getInspectionPlan } from '@/api/sb/inspectionPlan'

export default {
  name: 'AddInspectionRecord',
  data() {
    return {
      // 表单参数
      form: {
        recordCode: '自动生成',
        planId: null,
        planName: '',
        equipmentId: null,
        equipmentName: '',
        inspectorName: '',
        inspectionDate: new Date().toISOString().split('T')[0], // yyyy-MM-dd 格式
        inspectionStartTime: null,
        inspectionEndTime: null,
        inspectionStatus: '0', // 默认待巡检
        inspectionResult: '0', // 默认正常
        remark: '',
        inspectionItems: []
      },
      // 巡检计划选项
      planOptions: [],
      // 设备选项
      equipmentOptions: [],
      // 巡检状态选项
      statusOptions: [
        { dictLabel: '待巡检', dictValue: '0' },
        { dictLabel: '巡检中', dictValue: '1' },
        { dictLabel: '已完成', dictValue: '2' },
        { dictLabel: '已取消', dictValue: '3' }
      ],
      // 当前选中的计划详情
      currentPlan: null,
      // 巡检项弹窗
      itemDialog: {
        visible: false,
        title: '新增巡检项'
      },
      // 巡检项表单
      itemForm: {
        itemName: '',
        itemStandard: '',
        requireImage: '0'
      },
      // 表单校验
      rules: {
        planId: [
          { required: true, message: '请选择巡检计划', trigger: 'change' }
        ],
        equipmentId: [
          { required: true, message: '请选择巡检设备', trigger: 'change' }
        ],
        inspectorName: [
          { required: true, message: '请输入巡检人姓名', trigger: 'blur' }
        ],
        inspectionDate: [
          { required: true, message: '请选择巡检日期', trigger: 'change' }
        ]
      },
      // 巡检项表单校验
      itemRules: {
        itemName: [
          { required: true, message: '巡检项名称不能为空', trigger: 'blur' }
        ],
        itemStandard: [
          { required: true, message: '巡检标准不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getPlans()
    this.generateRecordCode()
  },
  methods: {
    /** 生成巡检单编号 */
    generateRecordCode() {
      // 生成格式为 XJ + 年月日 + 3位随机数
      const date = new Date()
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const random = Math.floor(Math.random() * 900 + 100) // 生成100-999之间的随机数
      this.form.recordCode = `XJ${year}${month}${day}${random}`
    },
    /** 获取巡检计划列表 */
    getPlans() {
      getInspectionPlanList().then(response => {
        this.planOptions = response.rows || []
      })
    },
    /** 处理计划选择变化 */
    handlePlanChange(value) {
      if (!value) {
        this.equipmentOptions = []
        this.form.inspectionItems = []
        this.currentPlan = null
        return
      }
      
      // 获取计划详情
      getInspectionPlan(value).then(response => {
        if (response.data) {
          const plan = response.data
          console.log('获取到的巡检计划详情:', plan)
          this.currentPlan = plan
          this.form.planName = plan.planName
          
          // 获取该设备类型下的设备列表
          // 优先使用configId查询，然后尝试typeId
          if (plan.configId) {
            console.log('使用configId获取设备列表:', plan.configId)
            this.getEquipmentsByType(plan.configId)
          } else if (plan.typeId) {
            console.log('使用typeId获取设备列表:', plan.typeId)
            this.getEquipmentsByType(plan.typeId)
          } else {
            console.warn('巡检计划中没有typeId或configId，无法获取设备列表')
            // 临时添加一些调试选项
            this.$message.warning('未找到设备类型ID，添加测试选项')
            this.equipmentOptions = [
              {equipmentId: 1, equipmentName: '测试设备1 - 请先检查数据'},
              {equipmentId: 2, equipmentName: '测试设备2 - 请先检查数据'}
            ]
          }
          
          // 获取计划关联的巡检项
          this.getInspectionItemsByPlan(plan)
        }
      })
    },
    /** 根据设备类型获取设备列表 */
    getEquipmentsByType(typeId) {
      console.log('调用getAvailableEquipments API, typeId:', typeId)
      getAvailableEquipments(typeId).then(response => {
        console.log('获取到的设备列表:', response)
        this.equipmentOptions = response.data || []
        if (this.equipmentOptions.length === 0) {
          console.warn('获取到的设备列表为空，尝试获取所有设备')
          this.$message.warning('没有找到相关设备，尝试获取所有可用设备')
          
          // 尝试获取所有设备作为兜底方案
          getAllEquipments().then(allResp => {
            console.log('获取所有设备列表:', allResp)
            this.equipmentOptions = allResp.data || []
            
            if (this.equipmentOptions.length === 0) {
              console.warn('获取所有设备也为空')
              this.$message.warning('系统中没有可用设备')
              // 添加测试数据以验证UI显示正常
              this.equipmentOptions = [
                {equipmentId: 1, equipmentName: '测试设备1 - API返回空数据'},
                {equipmentId: 2, equipmentName: '测试设备2 - API返回空数据'}
              ]
            } else {
              console.log('成功获取到', this.equipmentOptions.length, '台所有设备')
              this.$message.success('已加载所有可用设备')
            }
          }).catch(error => {
            console.error('获取所有设备失败:', error)
            this.$message.error('获取所有设备失败: ' + error)
          })
        } else {
          console.log('成功获取到', this.equipmentOptions.length, '台设备')
        }
      }).catch(error => {
        console.error('获取设备列表失败:', error)
        this.$message.error('获取设备列表失败: ' + error)
        
        // 出错时尝试获取所有设备
        console.log('尝试获取所有设备作为备选')
        getAllEquipments().then(allResp => {
          this.equipmentOptions = allResp.data || []
          if (this.equipmentOptions.length > 0) {
            this.$message.success('已加载所有可用设备')
          }
        }).catch(err => {
          console.error('获取所有设备也失败:', err)
        })
      })
    },
    /** 获取计划关联的巡检项 */
    getInspectionItemsByPlan(plan) {
      // 清空当前巡检项
      this.form.inspectionItems = []
      
      if (plan && plan.typeId) {
        getItemsByConfigId(plan.typeId).then(response => {
          const items = response.rows || []
          if (items.length > 0) {
            this.form.inspectionItems = items.map(item => {
              return {
                itemId: item.itemId,
                itemName: item.itemName,
                itemStandard: item.itemStandard,
                requireImage: item.requireImage,
                checkValue: '',
                checkResult: '0' // 默认正常
              }
            })
          }
        })
      }
    },
    /** 打开新增巡检项弹窗 */
    addInspectionItem() {
      this.itemDialog.visible = true
      this.resetItemForm()
    },
    /** 重置巡检项表单 */
    resetItemForm() {
      this.itemForm = {
        itemName: '',
        itemStandard: '',
        requireImage: '0'
      }
      if (this.$refs.itemForm) {
        this.$refs.itemForm.resetFields()
      }
    },
    /** 提交巡检项表单 */
    submitItemForm() {
      this.$refs.itemForm.validate(valid => {
        if (valid) {
          // 将新巡检项添加到巡检项列表
          this.form.inspectionItems.push({
            itemId: null, // 标记为新增项
            itemName: this.itemForm.itemName,
            itemStandard: this.itemForm.itemStandard,
            requireImage: this.itemForm.requireImage,
            checkValue: '',
            checkResult: '0'
          })
          this.itemDialog.visible = false
          this.$modal.msgSuccess('添加巡检项成功')
        }
      })
    },
    /** 删除巡检项 */
    handleDeleteItem(index) {
      this.$confirm('确认删除该巡检项吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.form.inspectionItems.splice(index, 1)
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 提交表单 */
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.inspectionItems.length === 0) {
            this.$modal.msgError('请至少添加一个巡检项')
            return
          }
          
          // 组装提交数据
          const submitData = {
            recordCode: this.form.recordCode,
            planId: this.form.planId,
            equipmentId: this.form.equipmentId,
            inspectionDate: this.form.inspectionDate,
            inspectorName: this.form.inspectorName,
            inspectionStatus: this.form.inspectionStatus,
            inspectionResult: this.form.inspectionResult,
            remark: this.form.remark,
            inspectionItems: this.form.inspectionItems.map(item => {
              return {
                itemId: item.itemId,
                itemName: item.itemName,
                itemStandard: item.itemStandard,
                requireImage: item.requireImage,
                checkValue: item.checkValue,
                checkResult: item.checkResult
              }
            })
          }
          
          // 确保开始时间格式正确
          if (this.form.inspectionDate && this.form.inspectionStartTime) {
            // 将日期和时间作为分开的字段提交，让API层处理格式转换
            submitData.inspectionStartTime = this.form.inspectionStartTime;
            console.log('提交的日期:', this.form.inspectionDate);
            console.log('提交的时间:', this.form.inspectionStartTime);
          } else {
            // 如果没有设置时间，则不传递此字段
            delete submitData.inspectionStartTime;
          }
          
          console.log('提交的巡检单数据:', submitData);
          
          addInspectionRecord(submitData).then(response => {
            this.$modal.msgSuccess('新增成功')
            this.cancel()
          }).catch(error => {
            console.error('提交失败:', error)
            this.$modal.msgError('提交失败: ' + (error.message || error))
          })
        }
      })
    },
    /** 取消按钮 */
    cancel() {
      this.$router.push('/sb/Inspection-list')
    }
  }
}
</script> 

<style scoped>
.el-divider {
  margin: 24px 0;
}
</style> 